package cn.ly.gateway.core.datasource.unpooled;

import cn.ly.gateway.core.datasource.connection.DubboConnection;
import cn.ly.gateway.core.datasource.connection.HTTPConnection;
import cn.ly.gateway.core.mapping.HttpStatement;
import cn.ly.gateway.core.session.Configuration;
import cn.ly.gateway.core.datasource.Connection;
import cn.ly.gateway.core.datasource.DataSourceType;
import cn.ly.gateway.core.datasource.DataSource;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.rpc.service.GenericService;

public class UnpooledDataSource implements DataSource {

    private Configuration configuration;
    private HttpStatement httpStatement;
    private DataSourceType dataSourceType;

    public void setConfiguration(Configuration configuration) {
        this.configuration = configuration;
    }

    public void setHttpStatement(HttpStatement httpStatement) {
        this.httpStatement = httpStatement;
    }

    public void setDataSourceType(DataSourceType dataSourceType) {
        this.dataSourceType = dataSourceType;
    }

    @Override
    public Connection getConnection() {
        if (dataSourceType == DataSourceType.HTTP) {
            return new HTTPConnection(httpStatement.getUri());
        } else if (dataSourceType == DataSourceType.DUBBO) {
            String application = httpStatement.getApplication();
            String interfaceName = httpStatement.getInterfaceName();

            ApplicationConfig applicationConfig = configuration.getApplicationConfig(application);
            RegistryConfig registryConfig = configuration.getRegistryConfig(httpStatement.getApplication());
            ReferenceConfig<GenericService> referenceConfig = configuration.getReferenceConfig(interfaceName);

            return new DubboConnection(applicationConfig, registryConfig, referenceConfig);
        }
        throw new RuntimeException("DataSourceType：" + dataSourceType + "没有对应的数据源实现");
    }
}
